import 'base_generator.dart';

/// 模型生成器
class ModelGenerator extends BaseGenerator {
  static void generate(String name, Map<String, dynamic> options) {
    if (!BaseGenerator.isValidName(name)) {
      BaseGenerator.printError('模型名称格式不正确: $name');
      return;
    }

    final String moduleName = options['module'] ?? '';
    final bool withJson = options['with-json'] == true;
    final bool withHive = options['with-hive'] == true;

    final String className = BaseGenerator.toPascalCase(name);
    final String fileName = BaseGenerator.toSnakeCase(name);
    final String modulePath = BaseGenerator.getModulePath(moduleName);
    
    // 创建模型目录
    final String modelDir = moduleName.isEmpty ? 
        'lib/shared/models' : '$modulePath/data/models';
    BaseGenerator.createDirectoryIfNotExists(modelDir);
    
    // 生成模型文件
    final String modelPath = '$modelDir/$fileName.dart';
    final String modelContent = _generateModelContent(className, withJson, withHive);
    
    BaseGenerator.writeFile(modelPath, modelContent);
    
    BaseGenerator.printSuccess('模型', className, modelPath);
    
    if (withJson || withHive) {
      _printAdditionalInstructions(withJson, withHive);
    }
    
    _printUsageInstructions(className, withJson, withHive);
  }

  static String _generateModelContent(String className, bool withJson, bool withHive) {
    String imports = '''
import 'package:flutter/foundation.dart';
''';

    if (withJson) {
      imports += "import 'dart:convert';\n";
    }

    if (withHive) {
      imports += '''
import 'package:hive/hive.dart';

part '${BaseGenerator.toSnakeCase(className)}.g.dart';
''';
    }

    String classAnnotations = '';
    if (withHive) {
      classAnnotations = '@HiveType(typeId: 0) // 请根据项目需要修改typeId\n';
    }

    String fieldAnnotations = withHive ? '  @HiveField(0)\n' : '';
    String field2Annotations = withHive ? '  @HiveField(1)\n' : '';
    String field3Annotations = withHive ? '  @HiveField(2)\n' : '';
    String field4Annotations = withHive ? '  @HiveField(3)\n' : '';

    String jsonMethods = '';
    if (withJson) {
      jsonMethods = '''

  /// 从JSON创建实例
  factory $className.fromJson(Map<String, dynamic> json) {
    return $className(
      id: json['id'] as String? ?? '',
      name: json['name'] as String? ?? '',
      description: json['description'] as String? ?? '',
      createdAt: json['created_at'] != null 
          ? DateTime.parse(json['created_at'] as String)
          : DateTime.now(),
    );
  }

  /// 转换为JSON
  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'name': name,
      'description': description,
      'created_at': createdAt.toIso8601String(),
    };
  }

  /// 从JSON字符串创建实例
  factory $className.fromJsonString(String jsonString) {
    final Map<String, dynamic> json = jsonDecode(jsonString);
    return $className.fromJson(json);
  }

  /// 转换为JSON字符串
  String toJsonString() {
    return jsonEncode(toJson());
  }
''';
    }

    return BaseGenerator.generateFileHeader(
      className,
      '${className}数据模型'
    ) + '''
$imports

$classAnnotations${withHive ? 'class $className extends HiveObject {' : 'class $className {'}
$fieldAnnotations  final String id;
$field2Annotations  final String name;
$field3Annotations  final String description;
$field4Annotations  final DateTime createdAt;

  const $className({
    required this.id,
    required this.name,
    required this.description,
    required this.createdAt,
  });

  /// 创建副本
  $className copyWith({
    String? id,
    String? name,
    String? description,
    DateTime? createdAt,
  }) {
    return $className(
      id: id ?? this.id,
      name: name ?? this.name,
      description: description ?? this.description,
      createdAt: createdAt ?? this.createdAt,
    );
  }$jsonMethods

  @override
  bool operator ==(Object other) {
    if (identical(this, other)) return true;
    return other is $className &&
        other.id == id &&
        other.name == name &&
        other.description == description &&
        other.createdAt == createdAt;
  }

  @override
  int get hashCode {
    return Object.hash(id, name, description, createdAt);
  }

  @override
  String toString() {
    return '$className{id: \$id, name: \$name, description: \$description, createdAt: \$createdAt}';
  }

  /// 验证模型数据是否有效
  bool get isValid {
    return id.isNotEmpty && name.isNotEmpty;
  }

  /// 获取显示名称
  String get displayName {
    return name.isNotEmpty ? name : 'Unnamed $className';
  }

  /// 获取格式化的创建时间
  String get formattedCreatedAt {
    return '\${createdAt.year}-\${createdAt.month.toString().padLeft(2, '0')}-\${createdAt.day.toString().padLeft(2, '0')}';
  }

  /// 创建空实例
  factory $className.empty() {
    return $className(
      id: '',
      name: '',
      description: '',
      createdAt: DateTime.now(),
    );
  }

  /// 创建测试实例
  factory $className.mock() {
    return $className(
      id: 'mock_id_\${DateTime.now().millisecondsSinceEpoch}',
      name: 'Mock $className',
      description: 'This is a mock $className for testing purposes',
      createdAt: DateTime.now(),
    );
  }
}

/// ${className}列表扩展
extension ${className}ListExtension on List<$className> {
  /// 按名称排序
  List<$className> sortByName({bool ascending = true}) {
    final sorted = List<$className>.from(this);
    sorted.sort((a, b) => ascending 
        ? a.name.compareTo(b.name)
        : b.name.compareTo(a.name));
    return sorted;
  }

  /// 按创建时间排序
  List<$className> sortByCreatedAt({bool ascending = true}) {
    final sorted = List<$className>.from(this);
    sorted.sort((a, b) => ascending 
        ? a.createdAt.compareTo(b.createdAt)
        : b.createdAt.compareTo(a.createdAt));
    return sorted;
  }

  /// 根据名称搜索
  List<$className> searchByName(String query) {
    if (query.isEmpty) return this;
    return where((item) => 
        item.name.toLowerCase().contains(query.toLowerCase())).toList();
  }

  /// 获取有效的项目
  List<$className> get validItems {
    return where((item) => item.isValid).toList();
  }
}
''';
  }

  static void _printAdditionalInstructions(bool withJson, bool withHive) {
    print('\n📋 额外配置说明:');
    
    if (withHive) {
      print('');
      print('🔧 Hive配置:');
      print('1. 在pubspec.yaml中添加依赖:');
      print('   dependencies:');
      print('     hive: ^2.2.3');
      print('     hive_flutter: ^1.1.0');
      print('   dev_dependencies:');
      print('     hive_generator: ^2.0.1');
      print('     build_runner: ^2.4.7');
      print('');
      print('2. 运行代码生成:');
      print('   fvm flutter packages pub run build_runner build');
      print('');
      print('3. 在main.dart中注册适配器:');
      print('   await Hive.initFlutter();');
      print('   Hive.registerAdapter(YourModelAdapter());');
    }

    if (withJson) {
      print('');
      print('📄 JSON序列化:');
      print('已添加fromJson/toJson方法，可直接用于API数据转换');
    }
  }

  static void _printUsageInstructions(String className, bool withJson, bool withHive) {
    print('\n📋 使用说明:');
    
    print('1. 创建实例:');
    print('   final model = $className(');
    print('     id: \'1\',');
    print('     name: \'示例名称\',');
    print('     description: \'示例描述\',');
    print('     createdAt: DateTime.now(),');
    print('   );');
    
    if (withJson) {
      print('');
      print('2. JSON转换:');
      print('   // 从JSON创建');
      print('   final model = $className.fromJson(jsonData);');
      print('   // 转换为JSON');
      print('   final json = model.toJson();');
    }
    
    if (withHive) {
      print('');
      print('3. Hive存储:');
      print('   // 打开Box');
      print('   final box = await Hive.openBox<$className>(\'${BaseGenerator.toSnakeCase(className)}_box\');');
      print('   // 存储');
      print('   await box.put(model.id, model);');
      print('   // 读取');
      print('   final stored = box.get(model.id);');
    }

    print('');
    print('4. 常用操作:');
    print('   // 创建副本');
    print('   final updated = model.copyWith(name: \'新名称\');');
    print('   // 验证数据');
    print('   if (model.isValid) { /* 数据有效 */ }');
    print('   // 搜索列表');
    print('   final results = modelList.searchByName(\'关键词\');');
  }
}
''';
  }
}